<template>
  <!-- <el-table-column type="selection" width="55" /> -->
  <el-table-column class-name="order-table-col">
    <template #header>
      <div class="flex items-center" style="width: 100%">
        <el-checkbox
          v-model="selectAll"
          class="mr-20px"
          :indeterminate="selectAllIndeterminate"
          @change="handleSelectAll"
        />
        <div :style="{ width: 'calc(100% - 950px)' }" class="flex justify-center text-[#524E74]">
          商品信息
        </div>
        <div
          :style="{ width: orderTableHeadWidthList[1] + 'px' }"
          class="flex justify-center text-[#524E74]"
        >
          IP地址
        </div>
        <div
          :style="{ width: orderTableHeadWidthList[2] + 'px' }"
          class="flex justify-center text-[#524E74]"
        >
          地区/来源
        </div>
        <div
          :style="{ width: orderTableHeadWidthList[3] + 'px' }"
          class="flex justify-center text-[#524E74]"
        >
          下单信息
        </div>
        <div
          :style="{ width: orderTableHeadWidthList[4] + 'px' }"
          class="flex justify-center text-[#524E74]"
        >
          物流方式
        </div>
        <div
          :style="{ width: orderTableHeadWidthList[5] + 'px' }"
          class="flex justify-center text-[#524E74]"
        >
          订单总金额
        </div>
        <div
          :style="{ width: orderTableHeadWidthList[6] + 'px' }"
          class="flex justify-center text-[#524E74]"
        >
          留言/备注
        </div>
        <div
          :style="{ width: orderTableHeadWidthList[7] + 'px' }"
          class="flex justify-center text-[#524E74]"
        >
          状态
        </div>
      </div>
    </template>
    <template #default="scope">
      <el-table
        :ref="setOrderTableRef"
        :data="scope.row.items"
        :header-cell-style="headerStyle"
        :span-method="spanMethod"
        style="width: 100%"
        class="subTable"
        cell-class-name="subCell"
        header-cell-class-name="subHeaderCell"
      >
        <el-table-column min-width="326" prop="spuName">
          <template #header>
            <div
              class="h-[35px] flex items-center pl-[10px] pr-[10px]"
              style="background-color: var(--app-content-bg-color)"
            >
              <el-checkbox
                v-model="scope.row.selected"
                class="mr-[10px]"
                @change="handleSelectItems(scope.row)"
              />
              <span
                class="ml-10px text-[#231E47] text-[14px] cursor-pointer mr-20px py-[12px] font-normal"
                v-copyText="scope.row.no"
              >
                订单号：{{ scope.row.no }}
                <Icon icon="ep:copy-document" :size="12" class="cursor-pointer" />
              </span>
              <span
                class="mr-20px flex items-center text-[#231E47] text-[14px] py-[12px] font-normal"
              >
                下单链接：
                <el-tooltip width="200px" placement="top">
                  <template #content>
                    <div class="w-[300px] text-[12px] text-[#fff] cont">
                      https://huaban.com/follow/huaban.com/followhuaban.com/followhuaban.com/followhuaban.com/followhuaban.com/followhuaban.com/followhuaban.com/follow
                    </div>
                  </template>
                  <div class="cursor-pointer text-[#077BFF] text-cut max-w-[300px]">
                    https://huaban.com/follow/huaban.com/followhuaban.com/followhuaban.com/followhuaban.com/followhuaban.com/followhuaban.com/followhuaban.com/follow
                  </div>
                </el-tooltip>
              </span>
              <span class="mr-20px text-[#231E47] text-[14px] py-[12px] font-normal">
                创建时间：{{ formatDate(scope.row.createTime) }}
              </span>
              <span class="mr-20px text-[#231E47] text-[14px] py-[12px] font-normal">
                更新时间：{{ formatDate(scope.row.createTime) }}
              </span>
              <span class="mr-20px text-[#231E47] text-[14px] py-[12px] font-normal">
                历史购买情况：已下单5次，签收5次
              </span>
              <div
                class="ml-auto flex justify-between items-center w-[160px] text-[14px] font-normal btn"
              >
                <span class="text-[#3721FF] cursor-pointer">编辑</span>
                <span class="text-[#3721FF] cursor-pointer">详情</span>
                <span class="text-[#3721FF] cursor-pointer">备注</span>
              </div>
              <!-- <span>订单来源：</span>
              <dict-tag :type="DICT_TYPE.TERMINAL" :value="scope.row.terminal" class="mr-20px" />
              <span>支付方式：</span>
              <dict-tag
                v-if="scope.row.payChannelCode"
                :type="DICT_TYPE.PAY_CHANNEL_CODE"
                :value="scope.row.payChannelCode"
                class="mr-20px"
              />
              <span v-else class="mr-20px">未支付</span>
              <span v-if="scope.row.payTime" class="mr-20px">
                支付时间：{{ formatDate(scope.row.payTime) }}
              </span>
              <span>订单类型：</span>
              <dict-tag :type="DICT_TYPE.TRADE_ORDER_TYPE" :value="scope.row.type" /> -->
            </div>
          </template>
          <template #default="{ row }">
            <div class="flex flex-wrap">
              <div class="mb-[10px] mr-[10px] flex items-start">
                <div class="mr-[10px]">
                  <el-image
                    :src="row.picUrl"
                    class="!h-[86px] !w-[86px] roundec-[12px]"
                    fit="contain"
                    @click="imagePreview(row.picUrl)"
                  >
                    <template #error>
                      <div class="image-slot">
                        <icon icon="ep:picture" />
                      </div>
                    </template>
                  </el-image>
                </div>
                <div class="info">
                  <ElTooltip :content="row.spuName" placement="top">
                    <!-- overflow-ellipsis -->
                    <span class="two-line-text max-h-[45px] overflow-hidden">
                      {{ row.spuName }}12292_黄油饼干气垫粉扑干湿两用
                      饼干气垫粉扑干湿…12292_黄油饼干气垫粉扑干湿两用 饼干气垫粉扑干湿…
                    </span>
                  </ElTooltip>
                  <div class="mt-[5px] text-[#999] text-[14px] numbox"> 默认X1 </div>
                  <div class="text-[#999] text-[14px] numbox"> 商品ID: 69455884458895577 </div>
                </div>
              </div>

              <!-- <el-tag
                v-for="property in row.properties"
                :key="property.propertyId"
                class="mb-[10px] mr-[10px]"
              >
                {{ property.propertyName }}: {{ property.valueName }}
              </el-tag> -->
            </div>
          </template>
        </el-table-column>
        <el-table-column label="IP地址" align="center" prop="price" width="150">
          <template #default="{ row }">
            <!-- row.adjustPrice没用，纯占位，不输出row会报错 -->
            {{ row.adjustPrice }}
            172.0.0.1
          </template>
        </el-table-column>
        <el-table-column label="地区/来源" align="center" prop="afterSaleStatus" width="120">
          <template #default="{ row }">
            <!-- <dict-tag
              :type="DICT_TYPE.TRADE_ORDER_ITEM_AFTER_SALE_STATUS"
              :value="row.afterSaleStatus"
            /> -->
            {{ row.adjustPrice }}
            台湾高雄
          </template>
        </el-table-column>

        <el-table-column label="下单信息" width="160">
          <template #default>
            <!-- 快递发货  -->
            <div
              v-if="scope.row.deliveryType === DeliveryTypeEnum.EXPRESS.type"
              class="flex flex-col"
            >
              <span>买家：{{ scope.row.user?.nickname }}</span>
              <span>
                收货人：{{ scope.row.receiverName }} {{ scope.row.receiverMobile }}
                {{ scope.row.receiverAreaName }} {{ scope.row.receiverDetailAddress }}
              </span>
            </div>
            <!-- 自提  -->
            <div
              v-if="scope.row.deliveryType === DeliveryTypeEnum.PICK_UP.type"
              class="flex flex-col"
            >
              <span>
                门店名称：
                {{ pickUpStoreList.find((p) => p.id === scope.row.pickUpStoreId)?.name }}
              </span>
              <span>
                门店手机：
                {{ pickUpStoreList.find((p) => p.id === scope.row.pickUpStoreId)?.phone }}
              </span>
              <span>
                自提门店:
                {{ pickUpStoreList.find((p) => p.id === scope.row.pickUpStoreId)?.detailAddress }}
              </span>
            </div>
          </template>
        </el-table-column>

        <el-table-column align="center" label="物流方式" width="120">
          <template #default>
            <!-- <dict-tag :type="DICT_TYPE.TRADE_DELIVERY_TYPE" :value="scope.row.deliveryType" /> -->
            宅配到家
          </template>
        </el-table-column>
        <el-table-column align="center" label="订单总金额" width="120" prop="payPrice">
          <template #default>
            {{ floatToFixed2(scope.row.payPrice) + '元' }}
          </template>
        </el-table-column>
        <el-table-column align="center" label="留言/备注" width="120">
          <template #default>
            <!-- <dict-tag :type="DICT_TYPE.TRADE_ORDER_STATUS" :value="scope.row.status" /> -->
            <div class="flex items-start items">
              <div class="shrink-0 label">留言：</div>
              <div class="val">这是留言内容这是留言内容这是留言内容这是留言内容这是留言内容</div>
            </div>
            <div class="flex items-start items">
              <div class="shrink-0 label">备注：</div>
              <div class="val"></div>
            </div>
          </template>
        </el-table-column>
        <el-table-column align="center" label="订单状态" width="160">
          <template #default>
            <div class="flex justify-center items-center statusbox">
              <div
                class="px-[7px] py-[2px] flex items-center rounded-[5px]"
                :style="`background-color:${orderStatus[scope.row.status].bgColor}`"
              >
                <div class="w-[12px] h-[12px] rounded-[50%] relative mr-[4px] icon">
                  <img
                    :src="orderStatus[scope.row.status].icon"
                    class="w-full h-full object-contain absolute top-0 left-0"
                  />
                </div>
                <div
                  class="text-[12px] status txt"
                  :style="`color:${orderStatus[scope.row.status].color}`"
                >
                  {{ orderStatus[scope.row.status].name }}</div
                >
              </div>
            </div>

            <!-- <dict-tag :type="DICT_TYPE.TRADE_ORDER_STATUS" :value="scope.row.status" /> -->
          </template>
        </el-table-column>
        <!-- <el-table-column align="center" fixed="right" label="操作" width="160">
          <template #default>
            <slot :row="scope.row"></slot>
          </template>
        </el-table-column> -->
      </el-table>
    </template>
  </el-table-column>
</template>
<script lang="ts" setup>
import { DICT_TYPE } from '@/utils/dict'
import { DeliveryTypeEnum } from '@/utils/constants'
import { formatDate } from '@/utils/formatTime'
import { floatToFixed2 } from '@/utils'
import * as TradeOrderApi from '@/api/mall/trade/order'
import { OrderVO } from '@/api/mall/trade/order'
import type { TableColumnCtx, TableInstance } from 'element-plus'
import { createImageViewer } from '@/components/ImageViewer'
import type { DeliveryPickUpStoreVO } from '@/api/mall/trade/delivery/pickUpStore'
import { orderStatus } from '@/utils/order'

defineOptions({ name: 'OrderTableColumn' })

const props = defineProps<{
  list: OrderVO[]
  pickUpStoreList: DeliveryPickUpStoreVO[]
}>()

const headerStyle = ({ row, columnIndex }: any) => {
  // 表头第一行第一列占 8
  if (columnIndex === 0) {
    row[columnIndex].colSpan = 8
  } else {
    // 其余的不要
    row[columnIndex].colSpan = 0
    return {
      display: 'none'
    }
  }
}

const selectAll = ref(false)
const selectAllIndeterminate = ref(false)
const selectedRows = ref<any[]>([])

interface SpanMethodProps {
  row: TradeOrderApi.OrderItemRespVO
  column: TableColumnCtx<TradeOrderApi.OrderItemRespVO>
  rowIndex: number
  columnIndex: number
}

type spanMethodResp = number[] | { rowspan: number; colspan: number } | undefined
const spanMethod = ({ row, rowIndex, columnIndex }: SpanMethodProps): spanMethodResp => {
  const len = props.list.find(
    (order) => order.items?.findIndex((item) => item.id === row.id) !== -1
  )?.items?.length
  // 要合并的列，从零开始
  const colIndex = [3, 4, 5, 6, 7]
  if (colIndex.includes(columnIndex)) {
    // 除了第一行其余的不要
    if (rowIndex !== 0) {
      return {
        rowspan: 0,
        colspan: 0
      }
    }
    // 动态合并行
    return {
      rowspan: len!,
      colspan: 1
    }
  }
}

/** 解决 ref 在 v-for 中的获取问题*/
const setOrderTableRef = (el: TableInstance) => {
  if (!el) return
  // 只要第一个表也就是开始的第一行
  if (el.tableId !== 'el-table_2') {
    return
  }
  tableHeadWidthAuto(el)
}
// 头部 col 宽度初始化
const orderTableHeadWidthList = ref([300, 150, 120, 160, 120, 120, 120, 160])
// 头部宽度自适应
const tableHeadWidthAuto = (el: TableInstance) => {
  const columns = el.store.states.columns.value
  if (columns.length === 0) {
    return
  }
  columns.forEach((col: TableColumnCtx<TableInstance>, index: number) => {
    if (col.realWidth) {
      orderTableHeadWidthList.value[index] = col.realWidth
    }
  })
}
/** 商品图预览 */
const imagePreview = (imgUrl: string) => {
  createImageViewer({
    urlList: [imgUrl]
  })
}

/**
 * 全选切换
 */
const handleSelectAll = () => {
  const allSelected = selectAll.value // 获取全选状态
  selectAllIndeterminate.value = false
  selectedRows.value = allSelected
    ? props.list.map((order) => {
        return order
      })
    : [] // 取消所有选中
  // 更新每个订单的选中状态
  props.list.forEach((order) => {
    order.selected = allSelected
  })
}

/**
 * 单选选中切换
 */
const handleSelectItems = (row) => {
  const allSelected = props.list.every((order) => order.selected)
  selectAll.value = allSelected

  // 更新 indeterminate 状态
  const someSelected = props.list.some((order) => order.selected)
  selectAllIndeterminate.value = someSelected && !allSelected
}
</script>
<style lang="scss" scoped>
:deep(.order-table-col > .cell) {
  padding: 0;
}
:deep(.tableCell .cell) {
  padding-left: 0 !important;
  padding-right: 0 !important;
}

:deep(.el-table__cell.subCell) {
  border-bottom: 0px !important;
}
:deep(.el-table__cell.subHeaderCell) {
  border-bottom: 0px !important;
}
</style>
